package com.payment.controller.alast;

import com.google.common.base.Charsets;
import com.payment.config.dto.ResultDataDto;
import com.payment.entity.alast.paypalexecute.request.RequestExecutePaymentResult;
import com.payment.entity.alast.paypalexecute.response.ResponseExecutePaymentResult;
import com.payment.service.alast.PaymentAndResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 主要用在接收第三方支付的支付结果回调并处理
 * <p>
 * 对外第三方支付结果的回调使用
 *
 * @author lm
 * @date 2021/1/20 14:12
 */
@RestController
@Api(description = "接收和处理支付结果回调的控制类")
@CrossOrigin
public class ResultCallBackController {
    private static Logger logger = Logger.getLogger(ResultCallBackController.class);
    @Autowired
    PaymentAndResultService payAndResultService;

    /**
     * 微信回调
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @PostMapping(value = "/wxNotify")
    public String wxNotify(HttpServletRequest request) {

        String resXml;
        try {
            InputStream inputStream = request.getInputStream();
            //将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                logger.info("微信回调catch里面IOException报异常：" + e);
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.info("微信回调finally里面IOException报异常：" + e);
                }
            }

            resXml = sb.toString();
            if (StringUtils.isBlank(resXml)) {
                String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return result;
            }
            String result = payAndResultService.wxNotify(resXml);
            logger.info("微信回调响应：" + result);
            return result;

        } catch (Exception e) {
            logger.info("微信回调try里面Exception:" + e);
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[请求异常]]></return_msg>" + "</xml> ";
            logger.info("微信回调响应：" + result);
            return result;
        }
    }

    /**
     * payPal的ipn回调
     * <p>
     * <p>
     * 传参必须要用 @RequestBody String reStr
     * <p>
     * HttpServletRequest request都收不到
     *
     * @param reStr
     */
    @CrossOrigin
    @PostMapping(value = "/ipn")
    public void ipn(@RequestBody String reStr) {
        logger.info("payPal的ipn回调Controller层：" + reStr);
        try {
            //去掉回车换行:replaceAll("\r\n", "")
            reStr = reStr.replaceAll("\\s*|\t|\r|\n", "");
            if (StringUtils.isBlank(reStr)) {
                return;
            }
            payAndResultService.ipn(reStr);
        } catch (Exception e) {
            logger.info("ipn回调try里面Exception:" + e);
        }
    }

    /**
     * 1,整合Smart Payment Buttons到页面
     * 2,用户点击付出按钮.
     * 3,按钮挪用 Orders API 建立生意业务
     * 4,进入paypal付出页面
     * 5,用户确认付出
     * 6,集成的PayPal继承挪用Orders API完成生意业务
     * (用户付出完成后，自动挪用 onApprove中的actions.order.capture()要领，该要领会猎取生意业务信息。末了要求应用服务器，服务器经由过程前端通报的orderID猎取定单概况，并处理我们本身的逻辑。)
     * 7,显现付出胜利信息
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @PostMapping(value = "/executePaymentResult", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "payPal执行付款的结果", response = ResponseExecutePaymentResult.class)
    public ResultDataDto executePaymentResult(@ApiParam @RequestBody RequestExecutePaymentResult request) {
        return null;
    }

    /**
     * payPal的webHook回调
     *
     * @param request
     */
    @CrossOrigin
    @PostMapping(value = "/webHook")
    public void webHook(HttpServletRequest request) {
        String resStr;
        try {
            //StreamUtils为springframework包的工具类,將HttpServletRequest的流直接转成String的方法
            //去掉回车换行:replaceAll("\r\n", "")
            resStr = StreamUtils.copyToString(request.getInputStream(), Charset.forName(Charsets.UTF_8.name())).replaceAll("\r\n", "");
            payAndResultService.webHook(resStr);
        } catch (Exception e) {
            logger.info("webHook回调try里面Exception:" + e);
        }
    }

    /**
     * stripe支付结果回调
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @PostMapping(value = "stripeCallback", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "stripe支付结果回调")
    public ResultDataDto stripeCallback(@ApiParam @RequestBody String request) {
        logger.info("Stripe回调的内容是：" + request.replaceAll("\n", ""));
        return payAndResultService.stripeCallback(request);
    }

    /**
     * stripe自动订阅结果回调
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @PostMapping(value = "stripeAutoSubCallback", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "stripe自动订阅结果回调")
    public ResultDataDto stripeAutoSubCallback(@ApiParam @RequestBody String request, HttpServletRequest re) {
        logger.info("Stripe自动订阅回调的内容是：" + request.replaceAll("\n", ""));
        return payAndResultService.stripeAutoSubCallback(re, request);
    }
}
